package com.wb3.meta.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by john on 2017/4/19.
 */
public class JsonUtil
{
    public static final String emptyPlaceholder = "";

    public static String toJsonString(Object object)
    {
        return JSON.toJSONString(object);
    }

    /**
     * gson
     */
    private static Gson gson = new GsonBuilder().create();

    public static <T> T toPojoObject(String jsongString, Class<T> clazz)
    {
        return JSON.parseObject(jsongString, clazz);
    }

    public static <T> T toPojoObject(Map<String, Object> map,  Class<T> clazz)
    {
        JSONObject json = new JSONObject(map);
        return json.toJavaObject(clazz);
    }

    public static Map<String, Object> jsonResponse(Object object)
    {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", 0);
        resultMap.put("data", object);
        return resultMap;
    }

    public static Map<String, Object> jsonResponse(int result, Object object)
    {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result", result);
        if (object == null)
        {
            resultMap.put("data", JsonUtil.emptyPlaceholder);
        }
        else
        {
            resultMap.put("data", object);
        }
        return resultMap;
    }

    public static HashMap<String,Object> toMap(String json){
        return gson.fromJson(json, new TypeToken<HashMap<String, Object>>() {}.getType());
    }
}
